package com.appspot.yozmcup;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oauth.signpost.OAuthConsumer;

import com.appspot.yozmcup.DAO.YozmDAO;
import com.appspot.yozmcup.util.UrlStore;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class YozmWriteServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(YozmWriteServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
		HttpSession session = req.getSession();
		OAuthConsumer consumer = (OAuthConsumer) session.getAttribute("consumer");
		String message = req.getParameter("message");
		String img_url = req.getParameter("img_url");
		
		JSONObject jsonResult = YozmDAO.getWrite(consumer, message, img_url);
		String redirectUrl = null;
		try {
			if(jsonResult != null && jsonResult.getInt("status") == 200){
				redirectUrl = jsonResult.getJSONObject("message").getString("permanent_url");
				res.sendRedirect(redirectUrl);
			}else{
				req.setAttribute("msg", "글 작성에 실패하였습니다.");
				RequestDispatcher rd = getServletContext().getRequestDispatcher(UrlStore.URL_ERROR);
				try {
					rd.forward(req, res);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			req.setAttribute("msg", "에러가 발생하였습니다.");
			RequestDispatcher rd = getServletContext().getRequestDispatcher(UrlStore.URL_ERROR);
			try {
				rd.forward(req, res);
			} catch (ServletException se) {
				se.printStackTrace();
			}
		}
	}
}
